// @ts-nocheck
import React, { Component } from 'react'
import { Card, Table, Button, Modal } from 'antd'
import { PlusCircleOutlined, ArrowRightOutlined } from '@ant-design/icons'
import { reqCategoryList, reqUpdateCategory, reqAddCategory } from '../../api/api'
import AddForm from './add-form'
import UpdateForm from './update-form'

export default class Category extends Component {

  state = {
    categoryList: [],
    subCategoryList: [],
    parentId: '0',
    parentName: '',
    showModal: 0
  }

  initColumns = () => {
    this.columns = [
      {
        title: '分类名称',
        dataIndex: 'name',
        key: 'name',
        width: '70%',
        align: 'left'
      },
      {
        title: '操作',
        width: '30%',
        render: (category) => ( // 此处的category表示包含被点击行的所有数据的对象
          <span>
            <Button type='link' onClick={() => this.updateCategory(category)}>修改</Button>
            {this.state.parentId === '0' ? <Button type='link' onClick={() => this.showSubCategory(category)}>查看子分类</Button> : null}
          </span>
        )
      },
    ];
  }
  // 展示添加分类对话框
  addCategroyModal = () => {
    // console.log (this.subCategoryItem)
    // 默认对应显示的值 initialValues不能动态  ?有错误
    if(typeof(this.subCategoryItem)!=="undefined" && this.state.parentId !== '0'){
      this.form.current.setFieldsValue({parentId:this.subCategoryItem._id})
    } else if (typeof(this.subCategoryItem)!=="undefined" && this.state.parentId === '0') {
      this.form.current.setFieldsValue({parentId: '0'})
    }
    
    this.setState({ showModal: 1 })
  }

  // 添加分类请求
  handleAddOk = async () => {
    // 验证后在发请求等操作 ？
    const {parentId,categoryName} = this.form.current.getFieldsValue()
    this.form.current.resetFields()
    const result = await reqAddCategory ({parentId,categoryName})
    // console.log (result)
    if (result.status === 0) {
      if (parentId === this.state.parentId) { // 添加的分类就是当前分类
        this.getCategoryList ()
        this.handleCancel()
      } else if (parentId === '0') {// 在二级分类下添加一级分类, 重新获取一级分类 但不用展示
        this.getCategoryList ('0')
        this.handleCancel()
      } else { // 在二级分类添加其他的二级分类
        this.getCategoryList ()
        this.handleCancel()
      }
    } else if (result.status ===1) {
      console.log (result.msg)
    }
  }

  // 展示修改分类对话框
  updateCategory = (item) => {
    // console.log(item)
    this.categoryItem = item // 将来render里面需要，先保存起来
    this.setState({ showModal: 2 }, ()=> {
      this.form.current.setFieldsValue({
        categoryName: this.categoryItem.name, // 解决异步问题，动态更新modal显示问题
    });
    })
    
  }

  // 修改分类请求
  handleUpdateOk =  () => {
    // 先表单验证 通过在继续
    this.form.current.validateFields ()
      .then (async()=> {
        // 隐藏 发请求更新  重新展示列表
      const categoryId = this.categoryItem._id
      const categoryName = this.form.current.getFieldValue('categoryName')
      // this.form.current.resetFields()
      const result = await reqUpdateCategory({ categoryId, categoryName })
      if (result.status === 0) {
        this.getCategoryList()
        this.handleCancel()
      } 
      })
      .catch ((err)=> {
        console.log (err.errorFields[0].errors)
      })
    
  }

  // 关闭modal————————————————————————————————————————————
  handleCancel = () => {
    // 清除数据
    this.form.current.resetFields ()
    this.setState({ showModal: 0 })
  }

  // 获取一级列表  parentId如果指定就根据指定发请求 没有指定就默认
  getCategoryList = async (parentId) => {
    parentId = parentId || this.state.parentId
    const result = await reqCategoryList({ parentId})
    // console.log (result)
    if (result.status === 0) {
      if (parentId === '0') {
        this.setState({ categoryList: result.data })
      } else {
        this.setState({ subCategoryList: result.data })
      }
    }
  }

  // 显示子分类列表
  showSubCategory = (category) => {
    const { _id, name } = category
    this.subCategoryItem = category // 存一下 添加二级分类名 默认展示动态切换使用
    // console.log (_id)
    this.setState({ parentId: _id, parentName: name },
      () => {
        // 该回调会在state和render之后触发(解决setstate异步更新的问题)
        // console.log (this.state.parentId)
        this.getCategoryList()
      }
    )

  }

  // 回退一级分类
  showCategoryList = () => {
    this.setState({
      parentId: '0',
      subCategoryList: [],
      parentName: ''
    })
  }



  UNSAFE_componentWillMount() {
    this.initColumns()
  }
  componentDidMount() {
    this.getCategoryList()
  }

  render() {
    // 结构state
    const { categoryList, showModal, parentId, subCategoryList, parentName } = this.state

    const categoryItem = this.categoryItem || {} // 如果还没有指定一个空对象 拿到当前点击行对象

    // 标题
    const title = parentId === '0' ? '一级分类列表' : (
      <span>
        <Button type='link' onClick={this.showCategoryList}>一级分类列表</Button>
        <ArrowRightOutlined />&nbsp;
        <span style={{ fontSize: '14px' }}>{parentName}</span>
      </span>
    )





    return (
      <Card title={title} extra={<Button onClick={this.addCategroyModal} type="primary" icon={<PlusCircleOutlined />}>添加</Button>} style={{ width: '100%' }}>
        <Table
          bordered
          sticky
          dataSource={parentId === '0' ? categoryList : subCategoryList}
          columns={this.columns}
          rowKey='_id'
          pagination={{ defaultPageSize: '6', showQuickJumper: true }} />

        <Modal title="添加分类" visible={showModal === 1} onOk={this.handleAddOk} onCancel={this.handleCancel}>
          <AddForm categoryList={categoryList} parentId={parentId} addform={form => this.form = form}/>
        </Modal>

        <Modal title="修改分类" visible={showModal === 2} onOk={this.handleUpdateOk} onCancel={this.handleCancel}>
          <UpdateForm categoryItemName={categoryItem.name} getform={form => this.form = form}></UpdateForm>
        </Modal>
      </Card>
    )
  }
}
